package com.yupi.springbootinit.blackIp;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.bloomfilter.BloomFilter;
import cn.hutool.core.collection.CollUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.Map;

@Component
public class BlackIpUtils {

    private static BitMapBloomFilter bloomFilter;


    // 判断Ip是否在黑名单中
    public static boolean isBlackIp(String ip){
        return bloomFilter.contains(ip);
    }

    // 重构bloomFilter
    public static void rebuildBloomFilter(String configIp){
        if (StringUtils.isBlank(configIp)){
            configIp = "{}";
        }
        Yaml yaml = new Yaml();
        Map map = yaml.loadAs(configIp, Map.class);
        // 获取ip黑名单
        List<String> blackIpList = (List<String>) map.get("blackList");
        synchronized (BlackIpUtils.class){
            if (CollUtil.isNotEmpty(blackIpList)){
                BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(1000);
                for (String ip : blackIpList){
                    bitMapBloomFilter.add(ip);
                }
                bloomFilter = bitMapBloomFilter;
            }else {
                bloomFilter = new BitMapBloomFilter(100);
            }
        }
    }

}
